package com.liyongjian.xhban.api;

import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.liyongjian.xhban.dto.BaseProperties;
import com.liyongjian.xhban.dto.SessionUser;
import com.liyongjian.xhban.exception.XHBanException;
import com.liyongjian.xhban.utils.JsonMapper;
import com.liyongjian.xhban.utils.MapUtils;



public class BaseController extends BaseProperties {

    public JsonMapper jsonMapper = new JsonMapper();

    private static Map<String, Object> tokenMap = new HashMap<String, Object>();

    public Map<String, Object> getRequestParameter(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        Enumeration<String> en = request.getParameterNames();
        while (en.hasMoreElements()) {
            String key = (String) en.nextElement();
            String value = request.getParameter(key);
            map.put(key, value);
        }
        return map;
    }


    protected void saveCurrentUser(String token, Long id) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        map.put("loginTime", new Date().getTime() + "");
        tokenMap.put(token, map);
    }


    @SuppressWarnings("unchecked")
    protected SessionUser getCurrentUser(String token) {
        SessionUser su = new SessionUser();
        if (!tokenMap.containsKey(token)) {
            throw new XHBanException("0001", "登录超时");
        }
        Map<String, Object> map = (Map<String, Object>) tokenMap.get(token);
        MapUtils.copyProperties(su, map);
        return su;
    }


    protected void removeCurrentUser(String token) {
        tokenMap.remove(token);
    }

}
